package com.example.springboothikaricp.utils;


import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;


/**
 *  数据库连接池工具类
 * @author lujunyi
 */
public class DbUtil {
	private static Logger log = LoggerFactory.getLogger(DbUtil.class);

	private static HikariDataSource dataSource = null;

	static {
		getDatasource();
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				closeDatasource();
			}
		});
	}

	/**
	 * 初始化连接池
	 * @return
	 */
	private static HikariDataSource getDatasource() {
		if (dataSource != null && !dataSource.isClosed()) {
			return dataSource;
		}
		synchronized (DbUtil.class) {
			if (dataSource != null && !dataSource.isClosed()) {
				return dataSource;
			}
			Properties properties = new Properties();
			try {
				properties.load(DbUtil.class.getResourceAsStream("/jdbc.properties"));
			} catch (IOException e) {
				throw new RuntimeException("not found jdbc.properties in classpath");
			}
			HikariConfig config = new HikariConfig();
			config.setDriverClassName(properties.getProperty("driverClassName"));
			config.setJdbcUrl(properties.getProperty("jdbcUrl"));
			config.setUsername(properties.getProperty("username"));
			config.setPassword(properties.getProperty("password"));
			config.setConnectionTestQuery("select 1");
			config.setMaximumPoolSize(gotInt(properties.getProperty("maxPoolSize")));
			config.setMaxLifetime(gotInt(properties.getProperty("maxLifetime")));

			HikariDataSource hikariDataSource = new HikariDataSource(config);
			dataSource = hikariDataSource;
			return dataSource;
		}

	}

	private static int gotInt(String value){
		if(value!=null && !value.trim().isEmpty()){
			try {
				return Integer.parseInt(value);
			}catch (NumberFormatException e){
				log.error("不是整数："+value,e);
			}
		}

		return 5;
	}

	/**
	 * 获取数据库连接
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		return getDatasource().getConnection();
	}
	
	/**
	 * 关闭数据源
	 */
	public static void closeDatasource() {
		log.info("datasource close");
		try {
			if (dataSource != null) {
				dataSource.close();
			}
		} catch (Throwable e) {
		}
	}
}
